<?php

class ImagesController extends AppController
{
	var $name = 'Images';
	var $uses = array('Image','Copyright');
	
	// Default Settings
	var $directory = 'files/Image/';
	var $allowedTypes = array('image/jpeg', 'image/gif', 'image/png');
	var $thumbsize = array(
						'small' => array('width'=>100, 'height'=>100),
						'medium'=> array('width'=>220, 'height'=>220)
					);
	
	var $paginate = array('fields'=>array('Image.id', 'Image.filename', 'Image.filesize', 'Image.alt', 'Image.type'),'limit'=>10, 'order'=>array('Image.created'=>'DESC'));
	
	function view($id)
	{
		$image = $this->Image->findById($id);
		$image['Image']['ext'] = $this->getExt($image['Image']['type']);
		$this->set('image', $image);
		
	}
	
	function admin_upload()
	{
		uses ('folder');
		
		$folder = new Folder($this->directory, false, 0755);
		$upload = array();
		
		$copyright_type = $this->Copyright->generateList();
		$this->set(compact('copyright_type'));
		
		if (isset($this->data) && $this->data['Image']['filename']['error'] == 0)
		{
			// Check that Filetype is valid
			if( !in_array( $this->data['Image']['filename']['type'] , $this->allowedTypes)){
				$this->Session->setFlash('Invalid File type: '.$this->data['Image']['filename']['type']);
				return false;
			}
			
			$valid_ext = $this->getExt($this->data['Image']['filename']['type']);
			// Explode file name and extention
			$myfile = $this->FileOps->explodeFilename($this->data['Image']['filename']['name']);
			if (!$valid_ext == $myfile['ext'])
			{
				$this->Session->setFlash('File extention does not match mimetype.  Please check this file is a valid' . $this->data['Image']['filename']['type'] . ' file.');
				break;
			}
			
			// Lets get the metadata first				
			$upload['type'] = $this->data['Image']['filename']['type'];			
			$upload['filesize'] = $this->data['Image']['filename']['size'];
			$upload['alt'] = $this->data['Image']['alt'];
			$upload['filename'] = $myfile['filename'];
			$upload['copyright_id'] = $this->data['Image']['copyright_id'];
			$upload['copyright_owner'] = $this->data['Image']['copyright_owner'];
			
			// The temporary file we need to copy once uploaded.
			$upload['tmp'] = $this->data['Image']['filename']['tmp_name'];
			
			if (!file_exists($this->directory . $upload['filename'] . '.' . $myfile['ext'])) {
				if (!($moved = $this->FileOps->movefile($this->directory, $upload['tmp'], $upload['filename'] . '.' . $myfile['ext'])))
				{
                	$this->Session->setFlash('File system save failed.');
					return false;
            	} else {
            		$this->Image->create();
            		$this->Image->save($upload);
					$this->Session->setFlash('Image successfuly uploaded');
					
					foreach($this->thumbsize as $thumb => $settings) :
						$thumbfile = $myfile['filename'] . '.' . $thumb . '.' . $myfile['ext'];
						if (!($this->createthumb($this->directory . $upload['filename'] . '.' . $myfile['ext'],$this->directory . $thumbfile, $settings['width'],$settings['width'])))
						{
							// #TODO: validation does not seem to work.
							//$this->Session->setFlash('Thumb failed');
							//return false;
						}
					endforeach;
				}
			} else {
				$this->Session->setFlash('File already exists.');
				return false;
			}
			
		} else if ($this->data['Image']['filename']['error'] == 4) {
			print_r('No File Selected');	
		}
	}
	
	function admin_index()
	{
		$images = $this->paginate();
		$this->set('file_dir', '/' . $this->directory);
		# OPTIMIZE: This could probably be done more ellegantly
		$thumbs = array();
		foreach ($images as $getthumb) :
			$ext = $this->getExt($getthumb['Image']['type']);
			$thumbs[$getthumb['Image']['id']] = $getthumb['Image']['filename'] . '.small' . $ext;
		endforeach;
		$this->set(compact('thumbs'));
		$this->set(compact('images'));
	}
	
	function admin_delete($id)
	{
		$file = $this->Image->findById($id);
		$ext = $this->getExt($file['Image']['filename']);
		$rootdir = ROOT . DS . APP_DIR . DS . WEBROOT_DIR . DS . 'files' . DS . 'Image' . DS;
				
		if ( unlink($rootdir . $file['Image']['filename'] . $ext) )
		{
			unlink($rootdir . $file['Image']['filename'] . '.small' . $ext);
			unlink($rootdir . $file['Image']['filename'] . '.medium' . $ext);
			
			$this->Image->delete($id);
			$this->Session->setFlash('File ' . $file['Image']['filename'] . ' removed');
			$this->redirect('/admin/images');
		} else {
			$this->Session->setFlash('Error deleting file');
			$this->redirect('/admin/images');
		}		
	}
	
	
	
	function getExt($type)
	{
		switch ($type) {
			case 'image/jpeg':
				$ext = ".jpg";
				break;
			case 'image/png':
				$ext = ".png";
				break;
			case 'image/gif':
				$ext = ".gif";
				break;
			default:
				$ext = ".jpg";
		}
		return $ext;
		
	}
	
	function createthumb($name,$filename,$new_w,$new_h)
	{
		$system=explode(".",$name);
		if (preg_match("/jpg|jpeg/",$system[1])){$src_img=imagecreatefromjpeg($name);}
		if (preg_match("/png/",$system[1])){$src_img=imagecreatefrompng($name);}
		$old_x=imageSX($src_img);
		$old_y=imageSY($src_img);
		if ($old_x > $old_y) 
		{
			$thumb_w=$new_w;
			$thumb_h=$old_y*($new_h/$old_x);
		}
		if ($old_x < $old_y) 
		{
			$thumb_w=$old_x*($new_w/$old_y);
			$thumb_h=$new_h;
		}
		if ($old_x == $old_y) 
		{
			$thumb_w=$new_w;
			$thumb_h=$new_h;
		}
		$dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
		imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); 
		if (preg_match("/png/",$system[1]))
		{
			imagepng($dst_img,$filename); 
		} else {
			imagejpeg($dst_img,$filename); 
		}
		imagedestroy($dst_img); 
		imagedestroy($src_img); 
	}
}
?>